<?php
class LZ_Account
{
	var $id = 'account_id';
	var $table = 'account';
	
	function LZ_Account()
	{
		$this->table = LZ_MYSQL_PREFIX.$this->table;
	}
	
	function add( $data = array())
	{
		global $db;
		$sql = make_insert_sql($this->table,$data);
		$db->query($sql);
		return $this->check_count($data['customer_id']);
	}
	
	function delete($id)
	{
		global $db;
		$arr = $this->get_one($id);
		$sql = "DELETE FROM $this->table WHERE $this->id = '$id';";
		$db->query($sql);
		return $this->check_count($arr['customer_id']);
	}
	
	function update($id,$data)
	{
		global $db;
		$sql = make_update_sql($this->table,$data, array($this->id => $id));
		return $db->query($sql);
	}
	
	function exists($email)
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE `email` = '$email' LIMIT 1";
		$r = $db->query($sql);
		return ($db->num_rows($r) > 0);
	}
	
	function check_admin_password($email,$password)
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE `email` = '$email' AND `password` = '$password' AND `status` = 'admin' LIMIT 1";
		return $db->get_one($sql);
	}
	
	function check_password($email,$password)
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE `email` = '$email' AND `password` = '$password' AND (`status` IS NULL OR `status` <> 'admin') LIMIT 1";
		return $db->get_one($sql);
	}
	
	function get_one($id)
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE `{$this->id}` = '$id';";
		return $db->get_one($sql);	
	}
	
	/*
	*Input: array
	*  search: search[key] like %{search[value]}%
	*  order: order by {order}
	*  desc? 'DESC': 'ASC'
	*  from total: LIMIT {from},{total}
	*  total: LIMIT {total}
	*/
	function get_list($data=array())
	{
		global $db;
		if ($data['select']) 
			$sql = "SELECT ".$data['select']." FROM `{$this->table}` WHERE 1=1 ";
		else
			$sql = "SELECT * FROM `{$this->table}` WHERE 1=1 ";
		if ($data['search'])
		{
			foreach($data['search'] as $key=>$val)
			{
				if ($val) $sql.= " AND $key LIKE '%$val%' ";
			}
		}
		$sql.= " AND customer_id='".$data['customer_id']."' ";
		$sql.= " ORDER BY ";
		
		if ($data['order'])
		{
			$sql.= $data['order'];
			$sql.= ($data['desc'])?' DESC':' ASC';
		}
		else
		{
			$sql.= "$this->id ASC";
		}

		

		if ($data['from'] && $data['total'])
		{
			$sql.=" LIMIT ".$data['from'].",".$data['total'];
		}
		else if ($data['total'])
		{
			$sql.=" LIMIT ".$data['total'];
		}
		$sql.= ';';
		return $db->get_all($sql);
	}
	
	function check_count($id)
	{
		global $db;
		include_once(LZ_BASEPATH.'model/customer.php');
		$customer = new LZ_Customer;
		if (!$id) return;
		$sql = "SELECT count(*) FROM $this->table WHERE customer_id=$id;";
		$re = $db->get_one($sql);
		$count = intval($re["count(*)"]);
		return $customer->update($id,array('account_count' => $count));
	}
}
?>
